# -*- coding: utf-8 -*-

#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################

## if SSL/HTTPS is properly configured and you want all HTTP requests to
## be redirected to HTTPS, uncomment the line below:
# request.requires_https()

if not request.env.web2py_runtime_gae:
    ## if NOT running on Google App Engine use SQLite or other DB
    db = DAL("postgres://web2py:xg2yKJPMAp@localhost/inVictus", pool_size=1, check_reserved=['all'])
else:
    ## connect to Google BigTable (optional 'google:datastore://namespace')
    db = DAL('google:datastore')
    ## store sessions and tickets there
    session.connect(request, response, db=db)
    ## or store session in Memcache, Redis, etc.
    ## from gluon.contrib.memdb import MEMDB
    ## from google.appengine.api.memcache import Client
    ## session.connect(request, response, db = MEMDB(Client()))

## by default give a view/generic.extension to all actions from localhost
## none otherwise. a pattern can be 'controller/function.extension'
response.generic_patterns = ['*'] if request.is_local else []
response.google_analytics_id = "UA-44727651-1"
## (optional) optimize handling of static files
# response.optimize_css = 'concat,minify,inline'
# response.optimize_js = 'concat,minify,inline'

#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - old style crud actions
## (more options discussed in gluon/tools.py)
#########################################################################

from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
auth = Auth(db)
crud, service, plugins = Crud(db), Service(), PluginManager()

## configure email
mail = auth.settings.mailer
mail.settings.server = 'logging' or 'smtp.gmail.com:587'
mail.settings.sender = 'you@gmail.com'
mail.settings.login = 'username:password'

## configure auth policy
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True
auth.settings.login_next = URL('default', 'home')
auth.settings.logout_next = URL('default', 'index')
auth.settings.register_next = URL('default', 'home')
auth.settings.profile_next = URL('default', 'home')
auth.settings.change_password_next = URL('default', 'home')
#auth.settings.retrieve_username_next = URL('index')
#auth.settings.retrieve_password_next = URL('index')
#auth.settings.request_reset_password_next = URL('user', args='login')
#auth.settings.reset_password_next = URL('user', args='login')
#auth.settings.verify_email_next = URL('user', args='login')
auth.settings.create_user_groups = False


## if you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc.
## register with janrain.com, write your domain:api_key in private/janrain.key
from gluon.contrib.login_methods.rpx_account import use_janrain
use_janrain(auth, filename='private/janrain.key')

from smarthumb import SMARTHUMB
box = (100, 100)

#########################################################################
## Define your tables below (or better in another model file) for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
##       'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################

def advanced_editor(field, value):
    return TEXTAREA(_id = str(field).replace('.','_'), _name=field.name, _class='text ckeditor', value=value, _cols=80, _rows=10)

## after defining tables, uncomment below to enable auditing
# auth.enable_record_versioning(db)


db.define_table('sessi',
                Field('sesso', 'string', required=True),
                Field('is_maschile', 'boolean', label='Maschile'),
                Field('is_femminile', 'boolean', label='Femminile'),                
                format='%(sesso)s')


auth.settings.extra_fields['auth_user'] = [Field('data_nascita', 'date', label=T("Data di nascita")),                                           
                                           Field('sesso_id', 'reference sessi', label=T("Sesso")),
                                           Field('peso', 'integer', label=T("Peso")),                                           
                                           Field("picture", "upload", label=T("Immagine")),
                                           Field("thumbnail", "upload", compute=lambda row:SMARTHUMB(row.picture, box))]
auth.define_tables(username=False, signature=False)


db.define_table('categorie_test',
                Field('categoria_test', 'string', required=True, label=T('Descrizione')),
                Field('descrizione', 'text', label=T('Informazioni'), widget=advanced_editor),
                Field("picture", "upload", label=T('Immagine')),
                Field("thumbnail", "upload"),
                format='%(categoria_test)s')
db.categorie_test.thumbnail.compute = lambda row: SMARTHUMB(row.picture, box)


db.define_table('test',
                Field('categoria_test_id', 'reference categorie_test'),
                Field('test', 'string'),
                Field('descrizione', 'text', widget=advanced_editor),
                Field("picture", "upload"),
                Field("thumbnail", "upload"),
                format='%(test)s')
db.test.thumbnail.compute = lambda row: SMARTHUMB(row.picture, box)


db.define_table('livelli',
                Field('livello', 'string', required=True),
                Field('ordine', 'integer', required=True),
                Field('descrizione', 'text', widget=advanced_editor),
                format='%(ordine)s - %(livello)s')


db.define_table('scale_valutazione',
                Field('descrizione', 'string', required=True),
                Field('sesso_id', 'reference sessi', label=T("Sesso")),
                Field('test_id', 'reference test', readable=False, writable=False),
                Field('pesoinizio', 'integer', required=True, default=0, label=T("Peso da")),
                Field('pesofine', 'integer', required=True, default=0, label=T("Peso a")),
                Field('etainizio', 'integer', required=True, default=0, label=T("Età da")),
                Field('etafine', 'integer', required=True, default=0, label=T("Età a")),
                format='%(descrizione)s')


db.define_table('risultati',
                Field('scala_valutazione_id', 'reference scale_valutazione'),
                Field('livello_id', 'reference livelli'),
                Field('risultato', 'integer', required=True, default=0))                            


####################################################################################################################################
# Candidature ######################################################################################################################
####################################################################################################################################
db.define_table('stati_sfida',
                Field('stato_sfida','string',label='Stato sfida'),
                Field('is_attesa', 'boolean', label='In attesa', default=None, required=False),
                Field('is_accettata', 'boolean', label='Accettata', default=None, required=False),
                Field('is_chiusa', 'boolean', label='Chiusa', default=None, required=False),
                Field('is_rifiutata', 'boolean', label='Rifiutata', default=None, required=False),
                format = "%(stato_sfida)s")


db.define_table('stati_candidatura',
                Field('stato_candidatura','string',label='Stato candidatura'),
                Field('is_attesa', 'boolean', label='In attesa di approvazione', default=None, required=False),
                Field('is_approvata', 'boolean', label='Approvata', default=None, required=False),
                Field('is_rifiutata', 'boolean', label='Rifiutata', default=None, required=False),
                format = "%(stato_candidatura)s")


db.define_table('sfide',
                Field('test_id', 'reference test', label='Test'),                
                Field('auth_user_id','list:reference auth_user', readable=False, writable=False),                
                Field('data_ora', 'datetime', default=request.now, required=True, label=T("Data*")),
                Field('stato_sfida_id','reference stati_sfida', label='Stato'))


db.define_table('candidatura',
                Field('sfida_id','reference sfide', readable=False, writable=False),
                Field('auth_user_id','reference auth_user', readable=False, writable=False),
                Field('stato_candidatura_id','reference stati_candidatura', label='Stato'),
                Field('data_ora', 'datetime', default=request.now, required=True, label=T("Data*")),
                Field('data_ora_approvazione', 'datetime', label=T("Data approvazione"), readable=False, writable=False),                                                                
                Field('video', 'string', label='Link video*', requires=IS_URL()),
                Field('risultato', 'integer', required=True, label='Risultato*'),
                Field('peso', 'integer', required=True, label=T("Peso*")),
                Field('age', 'integer', required=True, label=T("Età*")),
                Field('articolo', 'text', widget=advanced_editor, label=T("Articolo")))


db.define_table('punteggi',
                Field('candidatura_id', 'reference candidatura', required=True, readable=False, writable=False),
                Field('auth_user_id','reference auth_user', required=True, readable=False, writable=False),
                Field('test_id', 'reference test', required=True, readable=False, writable=False),
                Field('data_ora', 'datetime', required=True, readable=False, writable=False),
                Field('categoria_test_id', 'reference categorie_test', required=True, readable=False, writable=False),
                Field('livello_id', 'reference livelli', required=True, readable=False, writable=False),
                Field('risultato', 'integer', required=True, readable=False, writable=False),
                Field('punteggio', 'integer', required=True, readable=False, writable=False))


####################################################################################################################################
# Candidature ######################################################################################################################
####################################################################################################################################
db.define_table('commento_candidatura',
                Field('auth_user_id','reference auth_user', default=auth.user_id, readable=False, writable=False),
                Field('candidatura_id','reference candidatura', label='Candidatura'),
                Field('data_ora', 'datetime', default=request.now, update=request.now, writable=False, readable=False),
                Field('commento', 'text', widget=advanced_editor))


####################################################################################################################################
# Messaggistica ####################################################################################################################
####################################################################################################################################
db.define_table('messaggi',
                Field('auth_user_id', 'reference auth_user', label=T("Mittente")),
                Field('parent_id', 'reference messaggi', label=T("Genitore"), requires=IS_EMPTY_OR(IS_IN_DB(db, 'messaggi.id'))),
                Field('data_ora', 'datetime', default=request.now, writable=False, readable=False),
                Field('soggetto', 'string', required=True, label=T("Soggetto")),
                Field('corpo', 'text', required=True, label=T("Corpo")),
                format='%(id)s')


db.define_table('messaggio_destinatari',
                Field('messaggio_id', 'reference messaggi', label=T("Messaggio")),
                Field('auth_user_id', 'reference auth_user', label=T("Destinatario")),
                Field('is_letto', 'boolean', label=T("Letto")))      


####################################################################################################################################
# Messaggistica ####################################################################################################################
####################################################################################################################################
db.define_table('amicizie',
                Field('mittente_id', 'reference auth_user', readable=False, writable=False),
                Field('destinatario_id', 'reference auth_user', readable=False, writable=False),
                Field('is_accettata', 'boolean', default=False))

db.define_table('posts',
                Field('posted_by', 'reference auth_user', default=auth.user_id, readable=False, writable=False, label=T("Postato da")),
                Field('posted_to', 'reference auth_user', default=auth.user_id, readable=False, writable=False, label=T("Postato a")),
                Field('data_ora', 'datetime', default=request.now, readable=False, writable=False),
                Field('corpo', 'text', requires=IS_NOT_EMPTY(), label=T("")))
                            
db.define_table('post_likes',
                Field('post_id', 'reference posts', default=auth.user_id, readable=False, writable=False),
                Field('auth_user_id', 'reference auth_user', readable=False, writable=False),                
                Field('data_ora', 'datetime', default=request.now, readable=False, writable=False))

db.define_table('post_comments',
                Field('post_id', 'reference posts', readable=False, writable=False),
                Field('auth_user_id', 'reference auth_user', default=auth.user_id, readable=False, writable=False),
                Field('data_ora', 'datetime', default=request.now, writable=False, readable=False),
                Field('corpo', 'text', label=T("")))


def name_of(user):
    return '%(first_name)s %(last_name)s' % user


def getUserFriends(auth_user_id=auth.user_id):
    myfriends = [row.destinatario_id for row in db(db.amicizie.mittente_id==auth_user_id)(db.amicizie.is_accettata==True).select(db.amicizie.destinatario_id)]
    friendsofmine = [row.mittente_id for row in db(db.amicizie.destinatario_id==auth_user_id)(db.amicizie.is_accettata==True).select(db.amicizie.mittente_id)]
    return list(set(myfriends+friendsofmine))
